#include "messageunsenttable.h"
#include "sqlitemanager.h"
#include "appchat/accountmanager.h"

#include <QDebug>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlRecord>

namespace Sqlite {

MessageUnsentTable::MessageUnsentTable(QObject *parent) :
    QObject(parent)
{
}

void MessageUnsentTable::createTable()
{
    QString str = "CREATE TABLE IF NOT EXISTS MessagesUnsent (msgId INTEGER PRIMARY KEY,";
    str.append("conversationId INTEGER , ");
    str.append("sendingId INTEGER,");
    str.append("createdTime INTEGER,");
    str.append("receivedTime INTEGER,");
    str.append("senderId INTEGER,");
    str.append("receivedId INTEGER,");
    str.append("msg TEXT,");
    str.append("typeMsg INTEGER,");
    str.append("uid INTEGER)");

    QSqlQuery qry;
    qry.prepare(str );
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

void MessageUnsentTable::clearTable()
{

}

void MessageUnsentTable::insertMessage(const Converse::AbstractMessage *message)
{
    QString str = QString("INSERT OR REPLACE INTO MessagesUnsent (msgId,");
    str.append("conversationId, ");
    str.append("sendingId, ");
    str.append("createdTime, ");
    str.append("receivedTime, ");
    str.append("senderId, ");
    str.append("receivedId,");
    str.append("msg, ");
    str.append("typeMsg, ");
    str.append("uid) ");
    str.append("VALUES (%1, %2, %3, %4, %5, %6 , %7, '%8', %9, %10)");


    QString command = QString(str)
            .arg(message->createdTime())
            .arg(message->conversation().id())
            .arg(message->sendingId())
            .arg(message->createdTime())
            .arg(message->receivedTime())
            .arg(message->senderId())
            .arg(message->receiverId())
            .arg(message->message())
            .arg(message->type())
            .arg(AccountManager::instance()->getUserId());

    //qDebug() << "MessageUnsentTable::insertMessage" << command;

    QSqlQuery qry;
    qry.prepare(command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

void MessageUnsentTable::deleteMessage(const Converse::AbstractMessage *message)
{
    QString command = QString("DELETE  from MessagesUnsent where createdTime = %1")
            .arg(message->createdTime());

    qDebug() << command;

    QSqlQuery qry;
    qry.prepare(command);
    SqliteManager::instance()->doProcessSQLQuery(qry);
}

}
